package com.blogs.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;


import com.blogs.entity.AppConfig;
import com.blogs.entity.Feed;
import com.blogs.entity.MsgEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GetBlogSearch {
	public interface IMsgCallBack {
		public void onSuccess(ArrayList<Feed> feedList);
		public void onFailed();
	}
	private GetMsgTask timeLine;
    private IMsgCallBack callback;
    private String url="";
    public GetBlogSearch(int page,String key,IMsgCallBack callback) {
		// TODO Auto-generated constructor stub
		this.callback=callback;
		timeLine=new GetMsgTask(taskCallBack);
		try {
			key=URLEncoder.encode(key,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.url=AppConfig.GET_BLOG_SEARCH.replace("{0}", key).replace("{1}", page+"");
	}
	public void loadData()
	{
		timeLine.execute(url);
	}
    private GetMsgTask.onTaskCallBack taskCallBack=new GetMsgTask.onTaskCallBack() {
    	public void onSuccess(String result) 
    	{
    		GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<ArrayList<Object>> msg=null;
			try
			{
				msg=gson.fromJson(result,MsgEntity.class);
			}
			catch(Exception e)
			{
				callback.onFailed();
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				return;
			}
			ArrayList<Feed> feeds=new ArrayList<Feed>();
			Iterator<Object> iterator = msg.data.iterator();
			while (iterator.hasNext()) 
			{
				Map<String, Object> objs = (Map<String, Object>) iterator.next();
				Feed feed = new Feed(objs);
				feeds.add(feed);
			}
			callback.onSuccess(feeds);
    	};
    	public void onFailed() 
    	{
    		callback.onFailed();
    	};
    };
}
